<?php
namespace app\api\model;
use think\Db;
use think\Model;

class CommonModel extends Model{

    /**
     *  原生sql查询并分页输出
     *  
     *  @param  $sql
     *  @param  $page  当前页
     *  @param  $per   每页多少条数据
     *  @return array  二维数组 
     *              =>page:            当前页
     *              =>total_pages:     总页数
     *              =>total_record:    总记录数
     *              =>page_data:       分页数据
     */
    public static function sql_page($sql='',$page=1,$per=10){
        $sql = str_replace(array("\r\n", "\r", "\n"), " ", $sql);

        //1、总记录数量
        preg_match('/from\s+.+/i', $sql, $matchs);
        $temp_sql = 'select count(*) total ' . $matchs[0];
        $total_record = Db::query("$temp_sql")[0]['total'];
        //2、当前页
        $page = $page;
        //3、总页数
        $total_pages = ceil($total_record/$per);
        //4、数据
        $start  = ($page-1) * $per;
        $sql_list = $sql." limit $start,$per";
        $list = Db::query("$sql_list");
        
        
        $data = 
        [
            
            'page' => $page,
            'total_pages' => $total_pages,
            'total_record'  =>  $total_record,
            'page_data'  =>  $list,
        ];
        return $data;
        
    } 



}
